<template>
  <div class="login-wrap">
    <div class="login-container">
      <!-- el-form 表单组件 -->
      <!-- 为 el-form 表单组件添加验证规则 -->
      <el-form label-position="top" label-width="80px" :model="loginForm" :rules="loginFormRules" ref="loginFormEL">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click.prevent="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { login } from '@/api' // 按需加载
import { setToken } from '@/utils/auth'
export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      this.$refs.loginFormEL.validate((valid) => {
        if (valid) { // 验证通过，提交表单
          this.login()
        } else {
          return false
        }
      })
    },
    async login () {
      const { meta, data } = await login(this.loginForm)
      if (meta.status === 200) {
        this.$message({
          message: '登录成功',
          type: 'success'
        })
        // 将用户通过用户名+密码交换到的token（身份令牌）放到本地存储中，用以在别的地方使用
        // window.localStorage.setItem('token', data.token)
        setToken(data.token)
        this.$router.replace('/')
      } else {
        this.$message.error(`登录失败: ${meta.msg}`)
      }
    }
  }
}
</script>
<style scoped>
.login-wrap {
  height: 100%;
  background-color: #2f4050;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-container {
  width: 500px;
  height: 300px;
  background-color: #fff;
  border-radius: 10px;
  padding: 50px;
}
.login-btn {
  width: 100%;
}
</style>
